#include "QtGraphicsStateScene.h"
#include "QtGraphicsStateItem.h"
#include "QtGraphicsLinkItem.h"
#include "QtAnimGraphicsItem.h"

#include "qtbuttonpropertybrowser.h"
#include "qttreepropertybrowser.h"
#include "qtgroupboxpropertybrowser.h"

QtGraphicsStateScene::QtGraphicsStateScene(QObject* parent/* = 0*/):
	QGraphicsScene(parent)
{
	connect(this, SIGNAL(selectionChanged()), this, SLOT(selectionChange()));
}

QtGraphicsStateScene::~QtGraphicsStateScene(void)
{
}

void QtGraphicsStateScene::playAnim(bool bPlay)
{
	QList<QGraphicsItem*> itemsList = items();

	QtAnimGraphicsItem* pAnimItem = dynamic_cast<QtAnimGraphicsItem*>(parent());
	if (!pAnimItem)
	{
		return;
	}

	pAnimItem->playAnim();
}

void QtGraphicsStateScene::stateChanged(const QPointF& trans, const QVector3D& rot, const QPointF& scale)
{
	QList<QGraphicsItem*> items = selectedItems();
	if (items.size() > 0)
	{
		QtGraphicsStateItem* pItem = dynamic_cast<QtGraphicsStateItem*>( items.at(0) );
		if (pItem)
		{
			QtTransform newTrans;
			newTrans._translate = trans;
			newTrans._rotate = rot;
			newTrans._scale = scale;
			pItem->setState(newTrans);
		}
	}
}

void QtGraphicsStateScene::selectionChange()
{
	QList<QGraphicsItem*> items = selectedItems();
	if (items.size() > 0)
	{
		QtGraphicsStateItem* pItem = dynamic_cast<QtGraphicsStateItem*>( items.at(0) );
		QtGraphicsLinkItem* pLinkItem = dynamic_cast<QtGraphicsLinkItem*>( items.at(0) );

		if (pItem)
		{
			emit selected(pItem->getState()._translate, pItem->getState()._rotate, pItem->getState()._scale);
		}
		else if (pLinkItem)
		{
			emit changeProperties(pLinkItem->getPropertyWidget());
		}
	}
}

void QtGraphicsStateScene::load(QDataStream &dataStream)
{
	while(dataStream.atEnd() == false)
	{
		QString itemType;
		dataStream >> itemType;

		QtGraphicsLinkItem* item = 0;

		if (itemType == "QtGraphicsLinkItem")
		{
			item = new QtGraphicsLinkItem();
			addItem(item);
			//addItem(item);
			dataStream >> *item;
		}
	}
}

void QtGraphicsStateScene::save(QDataStream &dataStream)
{
	dataStream << QString(metaObject()->className());
	QGraphicsItem* item;
	foreach(item, items())
	{
		QtGraphicsLinkItem* boxItem = dynamic_cast<QtGraphicsLinkItem*>(item);
		if (boxItem)
		{
			dataStream << *boxItem;
		}
	}
}